<template>
  <div class="order-edit">
    <!-- Header -->
    <div class="header">
      <button class="back-button" @click="goBack">
        <i class="iconfont icon-arrow-left"></i> 返回
      </button>
      <h1 class="title">编辑订单</h1>
    </div>

    <!-- Main Content -->
    <div class="main-content">
      <!-- Customer Information -->
      <div class="form-section">
        <div class="section-header">
          <div class="header-line"></div>
          <span class="header-text">客户信息</span>
        </div>

        <div class="form-row">
          <div class="form-item">
            <label class="item-label required">客户姓名</label>
            <input
              v-model="formData.customerName"
              class="item-input"
              placeholder="请输入客户姓名"
              maxlength="20"
            />
          </div>

          <div class="form-item">
            <label class="item-label">联系方式</label>
            <input
              v-model="formData.phone"
              class="item-input"
              type="tel"
              placeholder="请输入手机号码"
              maxlength="11"
            />
          </div>
        </div>
      </div>

      <!-- Order Information -->
      <div class="form-section">
        <div class="section-header">
          <div class="header-line"></div>
          <span class="header-text">订单信息</span>
        </div>

        <div class="form-row">
          <div class="form-item">
            <label class="item-label required">服务类型</label>
            <div class="radio-group">
              <button
                v-for="(item, index) in typeList"
                :key="index"
                class="radio-item"
                :class="{ active: formData.type === item.name }"
                @click="formData.type = item.name"
              >
                {{ item.name }}
              </button>
              <button class="radio-item" @click="navTo('category')">
                <i class="iconfont icon-setting"></i>
                管理服务类型
              </button>
            </div>
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <label class="item-label required">开始日期</label>
            <div class="date-picker">
              <button
                class="date-input"
                @click="toggleStartDateCalendar"
              >
                <span>{{ startDateText }}</span>
                <i class="iconfont icon-calendar"></i>
              </button>
              <MiniCalendar
                v-if="showStartDateCalendar"
                v-model="startDateModel"
                :visible="showStartDateCalendar"
                mode="single"
                @apply="applyStartDateSelection"
                @close="showStartDateCalendar = false"
              />
            </div>
          </div>

          <div class="form-item">
            <label class="item-label required">结束日期</label>
            <div class="date-picker">
              <button
                class="date-input"
                @click="toggleEndDateCalendar"
              >
                <span>{{ endDateText }}</span>
                <i class="iconfont icon-calendar"></i>
              </button>
              <MiniCalendar
                v-if="showEndDateCalendar"
                v-model="endDateModel"
                :visible="showEndDateCalendar"
                mode="single"
                :min-date="startDateModel || minDate"
                @apply="applyEndDateSelection"
                @close="showEndDateCalendar = false"
              />
            </div>
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <label class="item-label">订单渠道</label>
            <div class="radio-group">
              <button
                v-for="(channel, index) in channelList"
                :key="index"
                class="radio-item"
                :class="{ active: formData.channel === channel.name }"
                @click="formData.channel = channel.name"
              >
                {{ channel.name }}
              </button>
              <button class="radio-item" @click="navTo('source')">
                <i class="iconfont icon-setting"></i>
                管理渠道
              </button>
            </div>
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <label class="item-label">备注</label>
            <textarea
              v-model="formData.note"
              class="item-textarea"
              placeholder="请输入备注"
              rows="3"
            ></textarea>
          </div>
        </div>
      </div>

      <!-- Financial Information -->
      <div class="form-section">
        <div class="section-header">
          <div class="header-line"></div>
          <span class="header-text">财务信息</span>
        </div>

        <div class="form-row">
          <div class="form-item">
            <label class="item-label required">订单总金额</label>
            <div class="input-with-unit">
              <input
                v-model="formData.totalAmount"
                class="item-input"
                type="text"
                placeholder="请输入总金额"
                @input="formatAmount('totalAmount')"
              />
              <span class="unit">元</span>
            </div>
          </div>

          <div class="form-item">
            <label class="item-label required">订金</label>
            <div class="input-with-unit">
              <input
                v-model="formData.deposit"
                class="item-input"
                type="text"
                placeholder="请输入订金"
                @input="formatAmount('deposit')"
              />
              <span class="unit">元</span>
            </div>
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <label class="item-label">尾款</label>
            <div class="input-with-unit">
              <input
                v-model="finalPayment"
                class="item-input"
                type="text"
                placeholder="自动计算"
                readonly
              />
              <span class="unit">元</span>
            </div>
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <label class="item-label">支付方式</label>
            <div class="radio-group">
              <button
                v-for="(method, index) in paymentMethodList"
                :key="index"
                class="radio-item"
                :class="{ active: formData.paymentMethod === method.name }"
                @click="formData.paymentMethod = method.name"
              >
                {{ method.name }}
              </button>
              <button class="radio-item" @click="navTo('payMethod')">
                <i class="iconfont icon-setting"></i>
                管理支付方式
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Submit Button -->
      <div class="submit-area">
        <button
          class="submit-button"
          :disabled="isSubmitting"
          @click="submitForm"
        >
          {{ isSubmitting ? "提交中..." : "保存修改" }}
        </button>
      </div>
    </div>
    <cate-modal
      v-if="showCateModal"
      ref="cateModalRef"
      @save="saveNewCategory"
      @close="showCateModal = false"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { get,post } from "@/request";
import { vToast } from "@/plugins/vToast";
import { format, parseISO } from "date-fns";
import MiniCalendar from "@/components/MiniCalendar.vue";
import cateModal from "./cateModal.vue";

const router = useRouter();
const route = useRoute();
const orderId = ref(route.params.id || route.query.id || "");

const showCateModal = ref(false);
const cateModalRef = ref(null);
const isSubmitting = ref(false);

// Form data
const formData = ref({
  customerName: "",
  phone: "",
  type: "",
  startDate: "",
  endDate: "",
  channel: "",
  note: "",
  totalAmount: "",
  deposit: "",
  paymentMethod: "",
});

// Data lists
const typeList = ref([]);
const channelList = ref([]);
const paymentMethodList = ref([]);

// Calendar state
const showStartDateCalendar = ref(false);
const showEndDateCalendar = ref(false);

// Get today's date for min date
const today = new Date();
const minDate = new Date(today.getFullYear(), today.getMonth(), today.getDate());

// Computed properties
const finalPayment = computed(() => {
  const total = parseFloat(formData.value.totalAmount) || 0;
  const deposit = parseFloat(formData.value.deposit) || 0;
  return (total - deposit).toFixed(2);
});

const startDateText = computed(() => {
  return formData.value.startDate ? format(new Date(formData.value.startDate), "yyyy-MM-dd") : "选择开始日期";
});

const endDateText = computed(() => {
  return formData.value.endDate ? format(new Date(formData.value.endDate), "yyyy-MM-dd") : "选择结束日期";
});

// Date models for MiniCalendar
const startDateModel = computed({
  get: () => formData.value.startDate ? new Date(formData.value.startDate) : null,
  set: (val) => {
    formData.value.startDate = val ? format(val, "yyyy-MM-dd") : "";
  }
});

const endDateModel = computed({
  get: () => formData.value.endDate ? new Date(formData.value.endDate) : null,
  set: (val) => {
    formData.value.endDate = val ? format(val, "yyyy-MM-dd") : "";
  }
});

// Methods
const goBack = () => {
  router.go(-1);
};

const navTo = (routeName) => {
  router.push({ name: routeName });
};

const getOrderDetail = async () => {
  try {
    const res = await get("/order/detail", { id: orderId.value });
    if (res.code === 200) {
      formData.value = {
        customerName: res.data.customer_name || "",
        phone: res.data.phone || "",
        type: res.data.type || "",
        startDate: res.data.start_date || "",
        endDate: res.data.end_date || "",
        channel: res.data.channel || "",
        note: res.data.note || "",
        totalAmount: res.data.total_amount || "",
        deposit: res.data.deposit || "",
        paymentMethod: res.data.payment_method || "",
      };
    }
  } catch (error) {
    console.error("获取订单详情失败:", error);
    vToast({ message: "获取订单详情失败" });
  }
};

const getTypeList = async () => {
  try {
    const res = await get("/category/list");
    if (res.code === 200) {
      typeList.value = res.data?.list || res.data || [];
      if (typeList.value.length > 0 && !formData.value.type) {
        formData.value.type = typeList.value[0].name;
      }
    }
  } catch (error) {
    console.error("获取服务类型失败:", error);
    vToast({ message: "获取服务类型失败" });
  }
};

const getChannelList = async () => {
  try {
    const res = await get("/source/list");
    if (res.code === 200) {
      channelList.value = res.data?.list || res.data || [];
      if (channelList.value.length > 0 && !formData.value.channel) {
        formData.value.channel = channelList.value[0].name;
      }
    }
  } catch (error) {
    console.error("获取渠道列表失败:", error);
    vToast({ message: "获取渠道列表失败" });
  }
};

const getPaymentMethodList = async () => {
  try {
    const res = await get("/payMethod/list");
    if (res.code === 200) {
      paymentMethodList.value = res.data?.list || res.data || [];
      if (paymentMethodList.value.length > 0 && !formData.value.paymentMethod) {
        formData.value.paymentMethod = paymentMethodList.value[0].name;
      }
    }
  } catch (error) {
    console.error("获取支付方式失败:", error);
    vToast({ message: "获取支付方式失败" });
  }
};

const toggleStartDateCalendar = () => {
  showStartDateCalendar.value = !showStartDateCalendar.value;
  showEndDateCalendar.value = false;
};

const toggleEndDateCalendar = () => {
  showEndDateCalendar.value = !showEndDateCalendar.value;
  showStartDateCalendar.value = false;
};

const applyStartDateSelection = () => {
  showStartDateCalendar.value = false;
};

const applyEndDateSelection = () => {
  showEndDateCalendar.value = false;
};

const formatAmount = (field) => {
  let value = formData.value[field];
  value = value.replace(/[^\d.]/g, "");
  const parts = value.split(".");
  if (parts.length > 2) {
    value = parts[0] + "." + parts.slice(1).join("");
  }
  if (parts.length === 2 && parts[1].length > 2) {
    value = parts[0] + "." + parts[1].substring(0, 2);
  }
  formData.value[field] = value;
};

const validateForm = () => {
  if (!formData.value.customerName) {
    vToast({ message: "请填写客户姓名" });
    return false;
  }

  if (!formData.value.type) {
    vToast({ message: "请选择服务类型" });
    return false;
  }

  if (!formData.value.startDate) {
    vToast({ message: "请选择开始日期" });
    return false;
  }

  if (!formData.value.endDate) {
    vToast({ message: "请选择结束日期" });
    return false;
  }

  if (!formData.value.totalAmount) {
    vToast({ message: "请填写订单总金额" });
    return false;
  }

  if (!formData.value.deposit) {
    vToast({ message: "请填写订金" });
    return false;
  }

  // 验证订金不能超过总金额
  const total = parseFloat(formData.value.totalAmount) || 0;
  const deposit = parseFloat(formData.value.deposit) || 0;
  if (deposit > total) {
    vToast({ message: "订金不能超过总金额" });
    return false;
  }

  return true;
};

const submitForm = async () => {
  if (!validateForm()) return;

  isSubmitting.value = true;

  const postData = {
    id: orderId.value,
    customer_name: formData.value.customerName,
    phone: formData.value.phone,
    type: formData.value.type,
    start_date: formData.value.startDate,
    end_date: formData.value.endDate,
    channel: formData.value.channel,
    note: formData.value.note,
    total_amount: parseFloat(formData.value.totalAmount) || 0,
    deposit: parseFloat(formData.value.deposit) || 0,
    final_payment: parseFloat(finalPayment.value) || 0,
    payment_method: formData.value.paymentMethod,
  };

  try {
    const res = await post("/order/update", postData);
    if (res.code === 200) {
      vToast({ message: "订单修改成功" });
      router.push({ name: "orderList" });
    } else {
      vToast({ message: res.msg || "订单修改失败" });
    }
  } catch (error) {
    console.error("提交订单失败:", error);
    vToast({ message: "订单修改失败，请稍后重试" });
  } finally {
    isSubmitting.value = false;
  }
};

const saveNewCategory = async (categoryData) => {
  try {
    const res = await post("/category/create", categoryData);
    if (res.code === 200) {
      vToast({ message: "服务类型新增成功" });
      showCateModal.value = false;
      await getTypeList();

      // 选中新创建的服务类型
      const newType = typeList.value.find(
        (item) => item.name === categoryData.name
      );
      if (newType) {
        formData.value.type = newType.name;
      }
    } else {
      vToast({ message: res.msg || "服务类型新增失败" });
    }
  } catch (error) {
    console.error("新增服务类型失败:", error);
    vToast({ message: "服务类型新增失败，请稍后重试" });
  }
};

// Lifecycle hooks
onMounted(() => {
  if (orderId.value) {
    getOrderDetail();
  }
  getTypeList();
  getChannelList();
  getPaymentMethodList();
});
</script>

<style scoped lang="less">
.order-edit {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  justify-content: space-between;

  .back-button {
    display: flex;
    align-items: center;
    background: none;
    border: none;
    color: #606266;
    cursor: pointer;
    font-size: 14px;
    margin-right: 20px;

    &:hover {
      color: var(--bs-theme-color);
    }
  }

  .title {
    margin: 0;
    font-size: 24px;
    font-weight: lighter;
    padding-right: 20px;
  }
}

.main-content {
  flex: 1;
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-section {
  margin-bottom: 30px;

  &:last-child {
    margin-bottom: 0;
  }
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e8e8e8;
}

.header-line {
  width: 4px;
  height: 16px;
  background-color: var(--bs-theme-color);
  margin-right: 10px;
  border-radius: 2px;
}

.header-text {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10px;
}

.form-item {
  flex: 0 0 50%;
  padding: 0 10px;
  margin-bottom: 20px;

  &.amount-item {
    display: flex;
    align-items: center;
  }
}

.item-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;

  &.required::after {
    content: "*";
    color: #f56c6c;
    margin-left: 4px;
  }
}

.item-input {
  width: 100%;
  height: 36px;
  padding: 0 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
  transition: border-color 0.2s;

  &:focus {
    outline: none;
    border-color: var(--bs-theme-color);
  }

  &[readonly] {
    background-color: #f5f7fa;
    cursor: not-allowed;
  }
}

.item-textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
  transition: border-color 0.2s;
  resize: vertical;

  &:focus {
    outline: none;
    border-color: var(--bs-theme-color);
  }
}

.input-with-unit {
  display: flex;
  align-items: center;

  .item-input {
    flex: 1;
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
  }

  .unit {
    width: 40px;
    height: 36px;
    line-height: 36px;
    text-align: center;
    background-color: #f5f7fa;
    border: 1px solid #dcdfe6;
    border-left: none;
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
    font-size: 14px;
    color: #909399;
  }
}

.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}

.radio-item {
  padding: 8px 15px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  color: #606266;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 6px;
  .iconfont {
    font-size: 14px;
  }
  &:hover {
    color: var(--bs-theme-color);
    border-color: #c6e2ff;
    background-color: #ecf5ff;
  }

  &.active {
    color: var(--bs-theme-color);
    border-color: var(--bs-theme-color);
    background-color: #ecf5ff;
  }
}

.date-picker {
  position: relative;
}

.date-input {
  width: 100%;
  height: 36px;
  padding: 0 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  color: var(--bs-text-color);
  transition: all 0.3s;
  font-size: 14px;

  &:hover {
    border-color: #c0c4cc;
  }

  .iconfont {
    color: var(--bs-text-color);
    font-size: 14px;
  }
}

.submit-area {
  display: flex;
  justify-content: center;
  margin-top: 30px;

  .submit-button {
    width: 200px;
    height: 40px;
    border: none;
    border-radius: 4px;
    background-color: var(--bs-theme-color);
    color: #fff;
    font-size: 14px;
    cursor: pointer;
    transition: background-color 0.2s;

    &:hover {
      background-color: #66b1ff;
    }

    &:disabled {
      background-color: #a0cfff;
      cursor: not-allowed;
    }
  }
}
</style>